/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.TimeClockServer.messages.rx;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

/**
 * This message represents the
 *
 * @author david
 */
public class UserTransactionMessage extends RxClockMessage {

    public class UserTransaction {

        private String transaction;

        public UserTransaction(String transaction) {
            this.transaction = transaction;
            System.out.println("Part Transaction: " + transaction);
        }
        
        public String getPrompt() {
            return transaction.substring(0, 5);
        }
        
        public char getMedia() {
            return transaction.charAt(5);
        }
        
        public String getData() {
            return transaction.substring(6);
        }
    };

    private final static SplitMessage MESSAGE_KEY = new SplitMessage(
            "[HDR]PN00[US]MSG-TIME[RS]");

    private final static String MSG_TIME = "MSG-TIME";
    private final static int FIRST_TRANSACTION_INDEX = 5;

    private boolean interractiveSupported = false;
    private boolean interractive = false;

    public UserTransactionMessage(byte[] msg) {

        super(msg, MESSAGE_KEY);
        String interractiveField = getPart(partCount() - 3);

        if (interractiveField.equals("I")) {
            interractiveSupported = true;
            interractive = true;
            
        } else if (interractiveField.equals("B")) {
            interractiveSupported = true;
            interractive = false;
        }
    }

    public boolean isInteractive() {
        return interractive;
    }

    public Date getMessageTime() throws ParseException {
        return DATE_FORMATTER.parse(getPart(MSG_TIME));
    }

    public ArrayList<UserTransaction> getTransactions() {

        ArrayList<UserTransaction> transactions =
                new ArrayList<UserTransaction>();

        int lastTransactionIndex = partCount() - 2;
        if (interractiveSupported) {
            lastTransactionIndex -= 2;
        }

        for (int index = FIRST_TRANSACTION_INDEX; 
                index <= lastTransactionIndex; index += 2) {
            transactions.add(new UserTransaction(getPart(index)));
        }

        return transactions;
    }
}
